import { Action } from "../Action/Action";
import { BehaviourNode } from "../BehaviorNode";

import { InputFmt, RunStatus } from "../IBehaviourTree";
/**
action = root.findNextAction(input);
if action is not empty then
action.Execute(request,  input)  //request是输出的请求
else
print “no action is available”
 */

/** 选择节点 */
export class Parallel extends BehaviourNode {
    children: BehaviourNode[] = []
    status: RunStatus = RunStatus.Completed;
    runIdx: number = 0;

    findNextAction<T extends Action>(): T {
        let actionNode: T;
        this.status = RunStatus.Running;

        /**检查子节点 */
        this.runIdx = 0;
        do {
            let childNode = this.children[this.runIdx];
            actionNode = childNode.findNextAction();
            this.runIdx++;
        } while (this.runIdx <= this.children.length - 1 && !actionNode)
        return actionNode;
    }
    enter(): boolean {

        return true
    }
    leave(): boolean {
        return true
    }
    async Tick(): Promise<any> {
        this.runIdx = 0;
        this.status = RunStatus.Running;
        /**检查子节点 */
        let isOk = false;
        let status: RunStatus;
        // 如果子节点有一个成功就返回Complete，全部失败就返回Failure,如果子节点返回Running就返回Running
        do {
            status = await this.children[this.runIdx].Tick();
            if (status == RunStatus.Completed
                || status == RunStatus.Running
                || (status == RunStatus.Failure && this.runIdx >= this.children.length - 1)
            ) {
                isOk = true;
            }
            this.runIdx++;
        } while (!isOk)

        this.status = status;
        // console.log(this.nodeName, status)
        return status;
    }

    addNode(node: BehaviourNode): void {
        this.children.push(node);
    }
    removeNode(node: BehaviourNode): void {
        if (this.children.includes(node)) {
            this.children.splice(this.children.indexOf(node), 1);
        }
    }
    HasNode(node: BehaviourNode): boolean {
        return this.children.includes(node);
    }
}